import { isRef, isReactive } from "vue"
import { isEmpty } from "@/utils"

function deepCloneArray(arr){
	const cloneArr = arr.map(item => {
		
		if(isEmpty(item)) return item;
		if(Array.isArray(item)){
			return deepCloneArray(item)
		}
		
		if(typeof item === 'object'){
			return deepCloneObj(item)
		}
		
		return item
	})
	
	return cloneArr
}

function deepCloneObj(object){
	if(object == null) return {}
	let obj = {}
	Reflect.ownKeys(object).forEach(key => {
		
		if(isEmpty(object[key])){
			obj[key] = object[key]
			return
		}
		
		if(Array.isArray(object[key])){
			obj[key] = deepCloneArray(object[key])
			return
		}
		
		if(typeof object[key] === 'object'){
			obj[key] = deepCloneObj(object[key])
			return
		}
		
		obj[key] = object[key]
	})
	
	return obj
}

function deepClone(object){
	if(!object) return object;
	if(isEmpty(object)) return object;
	
	if(isRef(object)){
		if(Array.isArray(object.value)){
			return deepCloneArray(object.value)
		}
		
		if(typeof object.value === 'object'){
			return deepCloneObj(object.value)
		}
		
		return object.value
	}
	
	if(isReactive(object)){
		if(Array.isArray(object)){
			return deepCloneArray(object)
		}
		
		return deepCloneObj(object)
	}
	
	return object
}

export default deepClone